package com.twu.biblioteca.view;

import com.twu.biblioteca.controller.UserController;
import com.twu.biblioteca.models.Library;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: ema93sh
 * Date: 8/9/13
 * Time: 5:48 PM
 */
public class ReserveView implements MenuItem {
    private final UserController userController;
    private Library library;

    public ReserveView(Library library, UserController userController) {
        this.library = library;
        this.userController = userController;
    }

    @Override
    public String displayTitle() {
        return "Reserve a Book";
    }

    @Override
    public void doWork() {
        if (!userController.isUserLoggedIn())
        {
            System.out.println("User is not logged In");
            return;
        }
        System.out.println("Enter the book ID/title:");
        Scanner in = new Scanner(System.in);
        String input = in.nextLine();
        boolean isDigit = isDigit(input);
        boolean reserved;
        if( isDigit )
        {
           int id = Integer.parseInt(input);
           reserved = library.reserve(id);
        }
        else
        {
           reserved = library.reserve(input);
        }

        printMessage(reserved);
    }

    private void printMessage(boolean reserved) {
        if (reserved)
            System.out.println("Thank You! Enjoy the book.");
        else
            System.out.println("Sorry we don't have that book yet.");
    }

    private boolean isDigit(String input) {          // Check if the input contains only digits
        try {
            Integer.parseInt(input);
            return true;
        }
        catch (NumberFormatException e)
        {
            return false;
        }
    }
}
